package com.dhcc.sds.standard.service.impl;

import com.alibaba.fastjson.JSONArray;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.dhcc.core.framework.base.service.impl.BaseServiceImpl;
import com.dhcc.core.framework.result.node.ZTreeNode;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.sds.standard.dao.SdsStandDataSourceMapper;
import com.dhcc.sds.standard.dto.TreeNode;
import com.dhcc.sds.standard.entity.SdsStandSourceEntity;
import com.dhcc.sds.standard.service.ISdsStandDataSourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 数据源定义表数据服务层接口
 *
 * @author lyh
 * @ClassName: SdsStandDataSourceServiceImpl
 * @Description: TODO
 */
@Service("sdsStandDataSourceService")
public class SdsStandDataSourceServiceImpl extends BaseServiceImpl<SdsStandDataSourceMapper, SdsStandSourceEntity> implements ISdsStandDataSourceService {
    @Autowired
    private SdsStandDataSourceMapper sourceMapper;

    @Override
    public List<SdsStandSourceEntity> page(Page<SdsStandSourceEntity> page, Map<String, Object> map) {
        return this.baseMapper.page(page, map);
    }

    @Override
    public List<SdsStandSourceEntity> list(Long parentId) {
        return this.baseMapper.list(parentId);
    }


    @Override
    public List<ZTreeNode> getEntityTree() {
        List<ZTreeNode> tree = this.baseMapper.tree();
        return tree;
    }

    @Override
    @Transactional
    public void importData(List<List<Object>> all, Long parentId) {
        SdsStandSourceEntity parentData = this.baseMapper.selectById(parentId);
        for (int i = 1; i < all.size(); i++) {
            List<Object> ls = all.get(i);
            String sourceCode = ls.get(0).toString();
            String sourceDesc = ls.get(1).toString();
            Integer isActive = (Integer) ls.get(2);
            String resume = ls.get(3).toString();

            // 判断数据源是否重复
            SdsStandSourceEntity datasource = new SdsStandSourceEntity();
            datasource.setSourceCode(sourceCode);
            datasource.setParentId(parentId);
            datasource = this.baseMapper.selectOne(datasource);
            if (CommonUtil.isEmpty(datasource)) {
                datasource = new SdsStandSourceEntity();
                datasource.setSourceCode(sourceCode);
                datasource.setSourceDesc(sourceDesc);
                datasource.setIsActive(isActive);
                datasource.setResume(resume);
                datasource.setParentId(parentId);
                datasource.setLevels(parentData.getLevels() + 1);
                datasource.insertAllColumn();
            } else {
                datasource = new SdsStandSourceEntity();
                datasource.setSourceCode(sourceCode);
                datasource.setSourceDesc(sourceDesc);
                datasource.setIsActive(isActive);
                datasource.setResume(resume);
                datasource.setParentId(parentId);
                datasource.setLevels(parentData.getLevels() + 1);
                datasource.updateById();
            }
        }
    }

    @Override
    public String getDataNameById(Long id) {
        SdsStandSourceEntity sdsStandSourceEntity = sourceMapper.selectById(id);
        if (CommonUtil.isEmpty(sdsStandSourceEntity)) {
            return "";
        } else
            return sdsStandSourceEntity.getSourceDesc();
    }

    @Override
    public List<SdsStandSourceEntity> exportData() {
        return this.baseMapper.exportData();
    }

    @Override
    public JSONObject getDataMap() {
        List<SdsStandSourceEntity> list = sourceMapper.selectList(null);
        JSONObject dataMap = new JSONObject();
        dataMap.put("", "");
        for (SdsStandSourceEntity sdsStandSourceEntity : list) {
            dataMap.put(String.valueOf(sdsStandSourceEntity.getId()), sdsStandSourceEntity.getSourceDesc());
        }
        return dataMap;
    }

    @Override
    public JSONArray getDataDescMap() {
        List<SdsStandSourceEntity> list = sourceMapper.selectList(null);
        JSONArray entityArry = new JSONArray();
        for (SdsStandSourceEntity sdsStandSourceEntity : list) {
            JSONObject officeObj = new JSONObject();
            String value = String.valueOf(sdsStandSourceEntity.getId());
            officeObj.put("value",value);
            officeObj.put("text",sdsStandSourceEntity.getSourceDesc());
//            dataMap.put(String.valueOf(sdsStandSourceEntity.getId()), sdsStandSourceEntity.getSourceDesc());
            entityArry.add(officeObj);
        }
        return entityArry;
    }

    @Override
    public List<TreeNode> getDataSourceTree(Long parentId) {
        List<TreeNode> treeList = new ArrayList<TreeNode>();
        List<TreeNode> treeParent = new ArrayList<TreeNode>();
        if (0l == parentId || null == parentId || "".equals(parentId)) {
            //dao.selectLevel()的作用是查询最外层的层级，也就是第一层
            //treeParent = single2Tree(this.baseMapper.selectLevel());
            treeParent = this.baseMapper.selectLevel();
        }else {
            //dao.selectSecondary(parentCCLNo）的作用是查询parentCCLNo的子级
            //treeParent = single2Tree(this.baseMapper.selectSecondary(parentId));
            treeParent = this.baseMapper.selectSecondary(parentId);
        }
        if (treeParent != null && !treeParent.isEmpty()) {
            for (TreeNode treeNode : treeParent) {
                //List<TreeNode> chileTree = single2Tree(this.baseMapper.selectSecondary(treeNode.getId()));
                List<TreeNode> chileTree = this.baseMapper.selectSecondary(treeNode.getId());
                //数据库中没有最后一层级的标志，这里根据的是：如果根据当前的id查不到子级，那么他就是最后一级
                if (null != chileTree && !chileTree.isEmpty()) {
                    //如果不是最后一级，继续调用getZUITree（）方法，并将查询到的值赋值给其父级的child属性
                    treeNode.setChildren(getDataSourceTree(treeNode.getId()));
                }
                treeList.add(treeNode);
            }
        }
        return treeList;
    }

    @Override
    public List<Tree<Long>> getDataSourceTree2() {
        List<SdsStandSourceEntity> sdsStandSourceEntities = this.baseMapper.selectList(null);
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setIdKey("id");
        treeNodeConfig.setParentIdKey("parentId");
        //构建树形
        List<Tree<Long>> trees = TreeUtil.build(sdsStandSourceEntities, 0L, treeNodeConfig, ((object, treeNode) -> {
            treeNode.setId(object.getId());//id
            treeNode.setParentId(object.getParentId());//父id
            treeNode.putExtra("text", object.getSourceDesc());
            if (isLastNode(object, sdsStandSourceEntities)) {
                // 如果是最后一个节点，则不添加state属性
            } else {
                treeNode.putExtra("state", "closed"); //默认全部折叠
            }
        }));
        return trees;
    }

    private boolean isLastNode(SdsStandSourceEntity currentNode, List<SdsStandSourceEntity> allNodes) {
        for (SdsStandSourceEntity node : allNodes) {
            if (node.getParentId().equals(currentNode.getId())) {
                return false; // 存在子节点，当前节点不是最底层节点
            }
        }
        return true; // 没有子节点，当前节点是最底层节点
    }
}
